<script lang="ts">
import {defineComponent} from 'vue'
import {useCacheImg} from "./cacheImg";
import {createUniqueString} from "@/utils";
import loadingImg from "@/assets/gif/5dadd6e959321e9fb3639aa848cbc2fc.gif"

// @ts-ignore
export default defineComponent({
  name: "CacheImg",
  props: {
    src: {
      type: String,
      default: () => ''
    },
    zipAndCache: {
      type: Boolean,
      default: () => true
    },
  },
  computed: {
    cacheId() {
      return this.id+this.src
    }
  },
  data() {
    return {
      id: createUniqueString(),
      // 创建一个视图监听
      observer: new IntersectionObserver(this.isIntersecting),
      // 记录元素是否可见
      imgInView: false,
    }
  },
  watch: {
    src: {
      immediate: true,
      async handler(val, oldVal) {
        if (this.$refs.imgRef) {
          this.$refs.imgRef.src = loadingImg
        }
        if (oldVal) {
          await useCacheImg.delTask(this.id + oldVal)
        }
        if (val) {
          await this.$nextTick()
          this.isIntersectingRun()
        }
      }
    },
  },
  mounted() {
    this.observer.observe(this.$refs.imgRef)
  },
  beforeUnmount() {
    this.observer.unobserve(this.$refs.imgRef)
    this.observer.disconnect()
    this.observer = null
    useCacheImg.delTask(this.cacheId)
  },
  methods: {
    isIntersecting(entries:IntersectionObserverEntry[]) {
      entries.forEach(entrie=>{
        if(entrie.target === this.$refs.imgRef) {
          this.imgInView = entrie.isIntersecting
        }
        this.isIntersectingRun()
      })
    },
    isIntersectingRun() {
      if(this.imgInView) {
        useCacheImg.getUrl(this.$refs.imgRef,this.src,this.cacheId,this.zipAndCache)
      } else {
        this.$nextTick(()=>{
          useCacheImg.delTask(this.cacheId)
        })
      }
    }
  }
})
</script>

<template>
  <img
    v-bind="$attrs"
    ref="imgRef"
    loading="lazy"
  >
</template>

<style scoped lang="scss">

</style>
